import tools from "@/common/tools.js"
import {
	uploadImage, //上传文件
	chat_sendMessage, //发送消息
	chatList, //聊天列表
	getchatMessage, //消息列表
	readAllMessage, //聊天已读取
	addFriend, //申请好友
	friendList, //好友列表
	numberOfFriendRequests, //好友申请数量
	approvingFriendRequests, //处理好友申请
	addBlacklist, //加入黑名单
	getblacklist, //黑名单列表
	removeBlackList, //移除黑名单
	removeMessage //删除消息 【清空聊天记录】
} from '@/common/path.js'
import {
	post
} from '@/common/axios.js'
import {
	emojiName,
	emojiMap,
	emojiUrl,
	list
} from '@/pages/chat/js_dk/emojiMap.js'
export default {
	namespaced: true,
	state: {
		url: 'ws://82.157.58.3:8010/webSocket/' + uni.getStorageSync('userInfo').id,
		emojiName: emojiName, //表情
		emojiMap: emojiMap, //表情
		emojiUrl: emojiUrl, //消息路径
		list: list, //消息插件功能底部
		webSocket: null, //webscoket创建
		user_id: uni.getStorageSync('userInfo').id,
		ta_id: '', //对面id
		user_avatar: uni.getStorageSync('userInfo').avatar, //用户信息
		message: [], //1v1消息内容列表
		messageList: [], //聊天列表
		friendInfoList: [], //好友列表
		blackList: [], //黑名单列表
		friendnum: '', //好友申请数量
	},

	getters: {

	},
	mutations: {
		SET_MESSAGE(state, data) { //同步接受消息 对应聊天1v1
			state.message.push(data)
		},
		SET_MESSAGEDATA(state, data) { //同步接受消息列表 对应聊天1v1
			state.message = data
		},
		SET_MESSAGELIST(state, data) { //聊过天的人
			state.messageList = data
		},
		SET_FRIEND(state, data) { //好友列表
			state.friendInfoList = data
		},
		SET_FRIENDNUM(state, data) { //好友申请数量
			state.friendnum = data
		},
		SET_BLACKLIST(state, data) { //黑名单列表
			state.blackList = data
		},
		SET_TAID(state, data) { //黑名单列表
			state.ta_id = data
			console.log('[对面id]',data)
		},


	},
	actions: {
		//添加taid
		setTaid({commit},args){
			commit('SET_TAID',args)
		},
		
		//删除消息
		removeMessageApi({
			commit,
			state
		}) {
			let args = {
				idList: [state.ta_id]
			}
			post(removeMessage, args).then(res => {
				if (res.code == 0) {
					commit('SET_MESSAGEDATA',[])
					tools.showToast(res.msg)
				} else {
					tools.showToast(res.msg)
				}
			})
		},

		//移出黑名单
		removeBlackListApi({
			dispatch
		}, args) {
			post(removeBlackList, args).then(res => {
				if (res.code == 0) {
					let data = {
						pageSize: 20,
						pageNum: 1,
					}
					dispatch('getblacklist', data)
					tools.showToast(res.msg)
				} else {
					tools.showToast(res.msg)
				}
			})
		},

		//黑名单列表
		getblacklist({
			state,
			dispatch,
			commit
		}, args) {
			post(getblacklist, args).then(res => {
				if (res.code == 0) {
					// console.log('[黑名单列表]', res)
					if (args.pageNum == 1) {
						commit('SET_BLACKLIST', res.data)
					} else {
						state.blackList.push(...res.data)
						commit('SET_BLACKLIST', state.blackList)
					}

				} else {
					commit('SET_BLACKLIST', [])
				}
			})
		},

		//加入黑名单
		addBlacklistApi({
			state
		}) {

			let data = {
				friendId: state.ta_id,
				userId: state.user_id
			}
			post(addBlacklist, data).then(res => {
				if (res.code == 0) tools.showToast('已添加到黑名单')
				else {
					tools.showToast(res.msg)
					setTimeout(() => {
						uni.navigateTo({
							url: '/pages/message/blacklist'
						})
					}, 1000)
				}
			})
		},

		//处理好友申请
		approvingFriendRequestsApi({
			commit
		}, args) {
			let data = {
				state: args.state,
				id: args.id
			}
			post(approvingFriendRequests, data).then(res => {
				tools.showToast(res.msg)
				if (res.code == 0) {
					if (data.state == 1) {
						args.data.state = 1
					} else {
						args.data.state = 2
					}
				}
			})
		},
		//好友申请数量
		numberOfFriendRequestsApi({
			commit
		}, args) {
			post(numberOfFriendRequests, args).then(res => {
				if (res.code == 0) {
					// console.log('好友申请数量', res.data)
					commit('SET_FRIENDNUM', res.data)
				} else {
					commit('SET_FRIENDNUM', 0)
				}
			})
		},
		//好友列表
		friendList({
			state,
			dispatch,
			commit
		}, args) {
			post(friendList, args).then(res => {
				if (res.code == 0) {
					// console.log('[好友列表]', res)
					if (args.pageNum == 1) {
						commit('SET_FRIEND', res.data)
					} else {
						state.friendInfoList.push(...res.data)
						commit('SET_FRIEND', state.friendInfoList)
					}

				} else {
					commit('SET_FRIEND', [])
					tools.showToast(res.msg)
				}
			})
		},

		//申请好友
		addFriend({
			state,
			dispatch
		}, args) {
			uni.showActionSheet({
				itemList: ['发送申请'],
				success: function(res) {
					if (res.tapIndex == 0) {
						post(addFriend, args).then(ret => {
							if (ret.code == 0) {
								tools.showToast('已提交申请')
							} else {
								tools.showToast(ret.msg)
							}
						})
					}
				},
				fail: function(res) {
					console.log(res.errMsg);
				}
			});
		},
		//聊天已读
		readAllMessageApi({
			state
		}, args) {
			post(readAllMessage, args).then(res => {
				// console.log('[已读]', res)
				if (res.code == 0) {

				}
			})
		},

		//发送消息
		chat_sendMessage({
			state,
			commit
		}, args = {}) {
			let data = {
				"userId": state.user_id,
				"taId": state.ta_id,
				"type": args.type,
				"content": args.content,
				"uid": state.user_id,
			}
			console.log('[vuex发送消息0]', data)
			commit('SET_MESSAGE', data)

			// post(chat_sendMessage, data).then(res => {
			// 	if (res.code == 0) {
			// 		commit('SET_MESSAGE', res.data)
			// 	} else if (res.code == 500) {
			// 		tools.showToast('消息发送失败请重新尝试')
			// 	} else {
			// 		tools.showToast(res.msg)
			// 	}
			// })
		},
		//获取聊天列表
		chatListApi({
			state,
			commit
		}, args) {
			// console.log('消息列表穿参',args)
			post(chatList, args)
				.then((res) => {
					if (res.code == 0) {
						if (args.pageNum == 1) {
							commit('SET_MESSAGELIST', res.data)
						} else {
							state.messageList.push(...res.data)
							commit('SET_MESSAGELIST', state.messageList)
						}
					} else {
						commit('SET_MESSAGELIST', [])
					}
				})
		},
		//获取对应用户聊天列表 1v1
		chatMessageApi({
			state,
			commit
		}, args = {}) {
			post(getchatMessage, args).then(res => {
				if (res.code == 0) {
					if (args.pageNum == 1) { //第一页
						commit('SET_MESSAGEDATA', res.data)
					} else {
						state.message.unshift(...res.data)
						commit('SET_MESSAGEDATA', state.message)
					}
				} else {
					tools.showToast(res.msg)
				}
			})
		},


		//弹出层功能
		showActionSheet({
			dispatch,
			state
		}) {
			uni.showActionSheet({
				itemList: ['查看个人主页', '举报', '拉黑', '清空聊天记录'],
				success: function(res) {
					console.log(res)
					if (res.tapIndex == 0) {
						uni.navigateTo({
							url: '/pages/user/modules/userInfo?id='+state.ta_id
						})
						// dispatch('chatHome')
					} else if (res.tapIndex == 1) {
						dispatch('chatReport')
					} else if (res.tapIndex == 2) {
						dispatch('addBlacklistApi') //拉黑
					} else if (res.tapIndex == 3) {
						dispatch('removeMessageApi') //清空聊天记录
					} else if (res.tapIndex == 4) {

					}
				},
				fail: function(res) {
					console.log(res.errMsg);
				}
			});
		},
		//发送语音
		sendAudio({
			state,
			dispatch
		}, args) {
			uni.uploadFile({
				url: uploadImage,
				filePath: args,
				// filePath: 'http://app.tiantai.com.cn/uploads/20200819/7103e314a4c998dcc5e2a75816d5bc4e.mp3',
				name: 'file',
				fileType: 'audio',
				success: (res) => {
					let analysisvideo = JSON.parse(res.data)
					if (analysisvideo.code == 0) {
						let data = {
							content: analysisvideo.data,
							type: 'audio',
							"uid": state.user_id,
						}
						console.log('[发送语音]', data)
						dispatch('chat_sendMessage', data)
					} else {
						tools.showToast(analysisvideo.msg)
					}
					uni.hideLoading()
				},
				file: (err) => {

					uni.hideLoading()
				},
				complete() {
					uni.hideLoading()
				}
			})

		},




		//跳转主页
		chatHome() {
			uni.navigateTo({
				url: '/'
			})
		},
		//举报
		chatReport() {
			
		},



		//弹到最底下
		pageScrollToMax() {
			uni.pageScrollTo({
				scrollTop: 999999, // 设置一个超大值，以保证滚动条滚动到底部
				duration: 100
			});
		},

		// image 图片 type 类型
		// call 视频通话
		// audio 音频文件
		// gift 礼物
		// icon表情包
		// text 文本

		//链接websocket
		openSocket({
			commit,
			dispatch,
			state
		}, ) {
			// 连接socket
			state.webSocket = uni.connectSocket({
				url: state.url,
				complete: (res) => {
					console.warn("[websocket]")
				}
			})
			// 监听连接成功
			dispatch('onOpen')
			// 监听接收信息
			dispatch('onMessage')
			// 监听断开
			dispatch('onClose')
			// 监听错误
			dispatch('onError')
		},
		// 监听连接成功
		onOpen({
			state
		}) {
			state.webSocket.onOpen(res => {
				console.warn('[连接成功]');
			})
		},
		// 监听接收信息
		onMessage({
			state,
			commit,
			dispatch
		}) {
			state.webSocket.onMessage(res => {
				let mode = JSON.parse(res.data)
				let type = mode['type']
				commit('SET_MESSAGE', mode)
				console.log('[收到的消息]', mode);
				let isMessage = true
				state.messageList.forEach(item => {
					if (item.taId == mode.taId) {
						// console.log('[消息]', item);
						item.unread = mode.unread
						item.content = mode.content
						item.type == mode.type
						isMessage = false
					}
				})
				if (isMessage) { //如果没聊过天，不去堆积假数据，刷新接口重新渲染
					dispatch('chatListApi')
				}
				if (type == "ping") {

				}
			})
		},
		// 监听断开
		onClose({
			state,
			dispatch
		}) {
			state.webSocket.onClose(res => {
				state.webSocket = null
				console.log('[socket连接已关闭3秒后重新链接]')
				setTimeout(function() {
					dispatch('openSocket') //重连
				}, 3000);
			})
		},
		// 监听错误
		onError({
			state,
			dispatch
		}) {
			state.webSocket.onError(res => {
				console.log('[监听错误]', res);
				dispatch('openSocket')
			})

		},
		//发送消息
		sendMessag({
			dispatch,
			commit,
			state,
		}, args = {}) {
			// console.log('[args]',args); 
			let data = {
				type: args.type, //消息类型 （图片，视频，语音,文字）
				user_id: state.user_id, //我的id
				ta_id: state.ta_id, //对方id
				content: args.content, //消息内容
				"uid": state.user_id,
			}
			// console.log('[穿参]', JSON.stringify(data));
			state.webSocket.send({
				data: JSON.stringify(data),
				success(res) {
					// console.log(res);
					if (res.errMsg == 'sendSocketMessage:ok') {
						dispatch('chat_sendMessage', data)
						// console.warn('[发送成功]',data);
					}

				},
				fail(err) {
					console.log('[发送失败]', err)
				}
			})
		},
		//消息列表
		cooseText() {
			console.log('[1]');
		},

		//礼物
		cooseGift({
			commit,
			dispatch
		}, args = {}) {
			dispatch('cooseText')
		},
		//发送表情
		cooseEmoji({
			commit,
			dispatch
		}, args = {}) {
			let data = {
				content: args,
				type: 'icon',
				"uid": state.user_id,
			}
			dispatch('sendMessag', data)
		},

		//视频
		chooseVideo({
			commit,
			dispatch,
			state
		}, args = {}) {
			let that = this
			uni.chooseVideo({
				count: 1,
				sourceType: ['camera', 'album'],
				compressed: true,
				success: function(event) {
					uni.showLoading({
						'title': '上传中...'
					})
					uni.uploadFile({
						url: uploadImage,
						filePath: event.tempFilePath,
						name: 'file',
						fileType: 'video',
						success: (res) => {
							let analysisvideo = JSON.parse(res.data)
							if (analysisImg.code == 0) {
								commit('SET_MESSAGE', analysisImg.data)
							} else {
								tools.showToast(analysisImg.msg)
							}
							uni.hideLoading()
						},
						fail: err => {
							uni.hideLoading()
						},
						complete() {
							uni.hideLoading()
						}
					})
				}
			});
		},
		//拍照
		chooseCamera({
			commit,
			dispatch,
			state
		}, args = {}) {
			let that = this
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['camera '], // 可以指定来源是相册还是相机，默认二者都有
				success: (event) => {
					uni.showLoading({
						'title': '上传中...'
					})
					uni.uploadFile({
						url: uploadImage,
						filePath: event.tempFilePaths[0],
						name: 'file',
						success: (res) => {
							let analysisImg = JSON.parse(res.data)
							if (analysisImg.code == 0) {
								let data = {
									content: analysisImg.data,
									type: 'image',
									"uid": state.user_id,
								}
								dispatch('sendMessag', data)
							} else {
								tools.showToast(analysisImg.msg)
							}
							uni.hideLoading()
						},
						fail: err => {
							uni.hideLoading()
							console.log(err);
						},
						complete() {
							uni.hideLoading()
						}

					})
				}
			})
		},
		//图片
		chooseImage({
			commit,
			dispatch,
			state
		}, args = {}) {
			let that = this
			uni.chooseImage({
				count: 1,
				sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album '], // 可以指定来源是相册还是相机，默认二者都有
				success: (event) => {
					uni.showLoading({
						'title': '上传中...'
					})
					uni.uploadFile({
						url: uploadImage,
						filePath: event.tempFilePaths[0],
						name: 'file',
						success: (res) => {
							let analysisImg = JSON.parse(res.data)
							if (analysisImg.code == 0) {
								let data = {
									content: analysisImg.data,
									type: 'image',
									"uid": state.user_id,
								}
								dispatch('sendMessag', data)
							} else {
								tools.showToast(analysisImg.msg)
							}
							uni.hideLoading()
						},
						fail: err => {
							uni.hideLoading()
							console.log(err);
						},
						complete() {
							uni.hideLoading()
						}

					})
				}
			})
		}
	},

}
